﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using Network_Toolbox.src;
using System.Net;
using Tamir.SharpSsh;
using Tamir.Streams;
using TelnetExpect;
using System.Net.Sockets;
using System.Threading;
using IVisio = Microsoft.Office.Interop.Visio;
using SnmpSharpNet;
using System.Net.NetworkInformation;

namespace Network_Toolbox
{
    public partial class fenetrePrincipale : Form
    {
        private Inventaire inventairePrincipal;
        private volatile List<String> resultats = new List<String>();
        private volatile List<List<String>> logs = new List<List<String>>();
        private static Semaphore _pool; 
        private System.ComponentModel.IContainer components;


        public fenetrePrincipale()
        {
            InitializeComponent();
            onglets.DrawItem += new DrawItemEventHandler(onglets_DrawItem);

            inventairePrincipal = new Inventaire("invent");
        }

        private void onglets_DrawItem(Object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;
            Brush _textBrush;
            Font _tabFont;
            Rectangle _tabBounds = onglets.GetTabRect(e.Index);
            Image image = imageList1.Images[0];
            Image image2 = imageList1.Images[2];
            Image image3 = imageList1.Images[1];
            Image image_check = imageList1.Images[3];

            switch (e.Index) { 
                case 0:
                    
                    if (e.State == DrawItemState.Selected)
                    {
                        // Draw a different background color, and don't paint a focus rectangle.
                        _textBrush = new SolidBrush(Color.Black);
                        g.FillRectangle(Brushes.Silver, e.Bounds);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Bold, GraphicsUnit.Pixel);
                        Rectangle imageRect = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 4, image2.Width, image2.Height);
                        g.DrawImage(image2, imageRect, 0, 0, image2.Width, image2.Height, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Regular, GraphicsUnit.Pixel);
                        e.DrawBackground();
                        Rectangle imageRect = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 2, image2.Width, image2.Height);
                        g.DrawImage(image2, imageRect, 0, 0, image2.Width, image2.Height, GraphicsUnit.Pixel);

                    }
                   
                    break; 
                case 1:
                    
                    if (e.State == DrawItemState.Selected)
                    {
                        // Draw a different background color, and don't paint a focus rectangle.
                        _textBrush = new SolidBrush(Color.Black);
                        g.FillRectangle(Brushes.Silver, e.Bounds);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Bold, GraphicsUnit.Pixel);
                        Rectangle imageRect2 = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 39, image3.Width, image3.Height);
                        g.DrawImage(image3, imageRect2, 0, 0, image3.Width , image3.Height, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Regular, GraphicsUnit.Pixel);
                        e.DrawBackground();
                        Rectangle imageRect2 = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 37, image3.Width, image3.Height);
                        g.DrawImage(image3, imageRect2, 0, 0, image3.Width, image3.Height, GraphicsUnit.Pixel);

                    }
                   
                    break;
                case 2:
                   
                    if (e.State == DrawItemState.Selected)
                    {
                        // Draw a different background color, and don't paint a focus rectangle.
                        _textBrush = new SolidBrush(Color.Black);
                        g.FillRectangle(Brushes.Silver, e.Bounds);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Bold, GraphicsUnit.Pixel);
                        Rectangle imageRect3 = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 74, image.Width, image.Height);
                        g.DrawImage(image, imageRect3, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Regular, GraphicsUnit.Pixel);
                        e.DrawBackground();
                        Rectangle imageRect3 = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 72, image.Width, image.Height);
                        g.DrawImage(image, imageRect3, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                    }
                    
                    break;
                case 3:

                    if (e.State == DrawItemState.Selected)
                    {
                        // Draw a different background color, and don't paint a focus rectangle.
                        _textBrush = new SolidBrush(Color.Black);
                        g.FillRectangle(Brushes.Silver, e.Bounds);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Bold, GraphicsUnit.Pixel);
                        Rectangle imageRect3 = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 109, image_check.Width, image_check.Height);
                        g.DrawImage(image_check, imageRect3, 0, 0, image_check.Width, image_check.Height, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Regular, GraphicsUnit.Pixel);
                        e.DrawBackground();
                        Rectangle imageRect3 = new Rectangle(e.Bounds.Left + 20, e.Bounds.X + 107, image_check.Width, image_check.Height);
                        g.DrawImage(image_check, imageRect3, 0, 0, image_check.Width, image_check.Height, GraphicsUnit.Pixel);

                    }

                    break;
                default:
                    if (e.State == DrawItemState.Selected)
                    {
                        // Draw a different background color, and don't paint a focus rectangle.
                        _textBrush = new SolidBrush(Color.Black);
                        g.FillRectangle(Brushes.Silver, e.Bounds);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Bold, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
                        _tabFont = new Font("Tahoma", (float)12.0, FontStyle.Regular, GraphicsUnit.Pixel);
                        e.DrawBackground();

                    }
                    break; 
            }     
            // Then draw the current tab button text      
            Rectangle paddedBounds=e.Bounds;     
            paddedBounds.Inflate(-2,-2);
            StringFormat _stringFlags = new StringFormat();
            _stringFlags.Alignment = StringAlignment.Far;
            _stringFlags.LineAlignment = StringAlignment.Center;
            g.DrawString(onglets.TabPages[e.Index].Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
        }

        private void button1_Click(object sender, EventArgs e)
        {
           Process.Start("ShunIPCalc.exe");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Process.Start("putty.exe");
        }

        private void buttonCharger_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.DefaultExt = "csv";
            openFile.Filter = "Fichier CSV | *.csv";
            openFile.ShowDialog();
            if (openFile.FileNames.Length > 0)
            {
                String chemin_fichier = openFile.FileNames[0];
                inventairePrincipal.chargerFichier(chemin_fichier);
                this.rafraichirAffichage();
            }
        }

        public void rafraichirAffichage()
        {
            int n;
            int compteurEquip = 0;
            int nbEquipTotal = inventairePrincipal.getTab_equipements().Count;
            //Début du rafraichiessement et initialisation de la barre de progression
            progressBarRafraichir.Visible = true;
            progressBarRafraichir.Value = 0;
            progressBarRafraichir.Maximum = nbEquipTotal;
            // si 'inventaire est vide on vide l'affichage
            if (this.inventairePrincipal.getTab_equipements().Count == 0)
            {
                    this.dataGridViewInventaire.Rows.Clear();
            }
            foreach (Equipement e in inventairePrincipal.getTab_equipements())
            {
                // si pas assez de ligne ajout d'une ligne dans l'affichage
                if (compteurEquip >= this.dataGridViewInventaire.RowCount)
                {
                    n = dataGridViewInventaire.Rows.Add();
                }
                else
                {
                    n = compteurEquip;
                }
                for (int i = 0; i < 11; i++)
                {
                    switch (i)
                    {
                        case 0 :
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getNom();
                                break;
                            }
                        case 1 :
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getIp();
                                break;
                            }
                        case 2:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getUser();
                                break;
                            }
                        case 3:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getMdp();
                                break;
                            }
                        case 4:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getMdp_enable();
                                break;
                            }
                        case 5:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getCommunaute();
                                break;
                            }
                        case 6:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getType_connexion();
                                break;
                            }
                        case 7:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getSerial_number();
                                break;
                            }
                        case 8:
                            {
                                dataGridViewInventaire.Rows[n].Cells[i].Value = e.getDescription();
                                break;
                            }
                        case 9:
                            {
                                String temp_cdp = "";
                                foreach (Port p in e.getTab_ports_voisins())
                                {
                                    if (p != null)
                                    {
                                        temp_cdp = temp_cdp + p.getEquipement_voisin() + "\n";
                                    }
                                }
                                dataGridViewInventaire.Rows[n].Cells[i].Value = temp_cdp;
                                break;
                            }
                        case 10:
                            {
                                String temp_cdp = "";
                                foreach (Port p in e.getTab_ports_voisins())
                                {
                                    if (p != null)
                                    {
                                        temp_cdp = temp_cdp + p.getNom() + "\n";
                                    }
                                }
                                dataGridViewInventaire.Rows[n].Cells[i].Value = temp_cdp;
                                break;
                            }
                    }
                }
                // Permet d'afficher au fur et à mesure
                dataGridViewInventaire.Refresh();
                // un equipement a été ajouté
                compteurEquip++;
                progressBarRafraichir.Increment(1);
            }
            foreach (DataGridViewRow rows in dataGridViewInventaire.Rows)
            {
                rows.ContextMenuStrip = contextMenuStrip1;
            }
            progressBarRafraichir.Visible = false;
            progressBarRafraichir.Value = 0;
        }

        private void buttonDiscover_Click(object sender, EventArgs e)
        {
            try
            {
                inventairePrincipal.discoverSnmpInvent();
            }
            catch (Exception exception)
            {
                int height = this.Size.Height;
                int Width = this.Size.Width;
                toolTip1.Show(exception.Message, this, 22, Height-78);
            }
            rafraichirAffichage();
        }

        private void buttonSauvegarde_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "Sauvegarde";
            saveFile.DefaultExt = "csv";
            saveFile.Filter = "Fichier CSV | *.csv";
            saveFile.FilterIndex = 1;
            saveFile.RestoreDirectory = true;
   
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                String chemin_sauvegarde = saveFile.FileName;
                String temp_cdp;
                StreamWriter sw = new StreamWriter(chemin_sauvegarde);

                sw.WriteLine("Nom;IP;User;Mot de passe;Mot de passe enable;Communaute;Type de connexion;Serial number;Description;Voisins");


                foreach (Equipement e1 in inventairePrincipal.getTab_equipements())
                {
                    temp_cdp = "";
                    Port[] tabTemp = e1.getTab_ports_voisins();
                    for (int i = 0; i < e1.getNbVoisin(); i++ )
                    {
                        if (i == e1.getNbVoisin() - 1)
                        {
                            temp_cdp = temp_cdp + tabTemp[i].ToString();
                        }
                        else
                        {
                            temp_cdp = temp_cdp + tabTemp[i].ToString() + " || ";
                        }

                    }
                    sw.WriteLine(e1.getNom()+";"+e1.getIp() + ";"+e1.getUser()+';'+e1.getMdp() + ";"+e1.getMdp_enable() + ";"+e1.getCommunaute() + ";"+e1.getType_connexion() + ";"+e1.getSerial_number() + ";"+e1.getDescription() + ";"+temp_cdp);
                }
                sw.Close();
            }
 

        }

        private void ajoutPlageIP(int ip1A, int ip1B, int ip1C, int ip1D, String ip2,String comm)
        {
            int a = ip1A;
            int b = ip1B;
            int c = ip1C;
            int d = ip1D;

            while(a < 255)
            {
                while(b < 255)
                {
                    while(c < 255)
                    {
                        while(d < 255)
                        {
                            String ip = Convert.ToString(a) + "." + Convert.ToString(b) + "." + Convert.ToString(c) + "." + Convert.ToString(d);
                            this.inventairePrincipal.ajoutEquipement(ip, comm);
                            if (ip.Equals(ip2))
                            {
                                // Sortie de boucle
                                a = 255;
                                b = 255;
                                c = 255;
                                d = 255;
                            }
                            d++;
                        }
                        d = 1;
                        c++;
                    }
                    c = 1;
                    b++;
                }
                b = 1;
                a++;
            }
            rafraichirAffichage();

        }

        private void buttonChargerAdresse_Click(object sender, EventArgs e)
        {
            try
            {
                int ip1A = Convert.ToInt16(textBoxAdresse1A.Text);
                int ip1B = Convert.ToInt16(textBoxAdresse1B.Text);
                int ip1C = Convert.ToInt16(textBoxAdresse1C.Text);
                int ip1D = Convert.ToInt16(textBoxAdresse1D.Text);
                int ip2A = Convert.ToInt16(textBoxAdresse2A.Text);
                int ip2B = Convert.ToInt16(textBoxAdresse2B.Text);
                int ip2C = Convert.ToInt16(textBoxAdresse2C.Text);
                int ip2D = Convert.ToInt16(textBoxAdresse2D.Text);
                String ip2 = textBoxAdresse2A.Text + "." + textBoxAdresse2B.Text + "." + textBoxAdresse2C.Text + "." + textBoxAdresse2D.Text;

                if (textBoxCommunaute.Text.Length != 0)
                {
                    if (ip1A < ip2A)
                    {
                        ajoutPlageIP(ip1A, ip1B, ip1C, ip1D, ip2, textBoxCommunaute.Text);
                    }
                    else if (ip1A == ip2A)
                    {
                        if (ip1B < ip2B)
                        {
                            ajoutPlageIP(ip1A, ip1B, ip1C, ip1D, ip2, textBoxCommunaute.Text);
                        }
                        else if (ip1B == ip2B)
                        {
                            if (ip1C < ip2C)
                            {
                                ajoutPlageIP(ip1A, ip1B, ip1C, ip1D, ip2, textBoxCommunaute.Text);
                            }
                            else if (ip1C == ip2C)
                            {
                                if (ip1D <= ip2D)
                                {
                                    ajoutPlageIP(ip1A, ip1B, ip1C, ip1D, ip2, textBoxCommunaute.Text);
                                }
                                else
                                {
                                    MessageBox.Show("Plage d'adresse IP invalide");
                                }
                            }
                            else
                            {
                                MessageBox.Show("Plage d'adresse IP invalide");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Plage d'adresse IP invalide");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Plage d'adresse IP invalide");
                    }
                }
                else
                {
                    MessageBox.Show("Veuillez remplir le champ comunauté");
                }
            }
            catch (Exception execptio)
            {
                MessageBox.Show("Veuillez remplir tous les champs");
                Console.WriteLine(execptio.StackTrace);
            }

        }

        private void sauvegarderLaConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String add;
            String login;
            String mdp;
            String mdpEn;
            String typeCon;
            String resultat = "";
            DateTime Maintenant = DateTime.Now;
            String DateMaintenant = Maintenant.ToString("yy-MM-dd_HH'h'mm");

            Regex maRegleNettoyage = new Regex(@".*#.*|show running-config|Building configuration...|^\n");
            Regex maRegleHostname = new Regex(@"hostname .*\n");
            Regex maRegleSuppHost = new Regex(@"hostname ([^\s]*)(\s)*");
            FolderBrowserDialog saveFile = new FolderBrowserDialog();
            saveFile.ShowNewFolderButton = true;
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                
                String chemin_sauvegarde = saveFile.SelectedPath;
                Console.WriteLine(chemin_sauvegarde);
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    add = row.Cells[1].Value.ToString();
                    try
                    {
                        login = row.Cells[2].Value.ToString();
                        mdp = row.Cells[3].Value.ToString();
                        mdpEn = row.Cells[4].Value.ToString();
                        typeCon = row.Cells[6].Value.ToString();
                   

                        if (typeCon == "ssh")
                        {
                            SshShell ssh = new SshShell(add, login, mdp);
                            try
                            {
                                ssh.Connect();
                            }
                            catch (Exception e1)
                            {
                                MessageBox.Show("Erreur : " + e1.Message);
                            }
                            Console.WriteLine("OK\n");
                            resultat = CiscoExpectSauvConf(ssh, mdpEn, "show running-config");
                            if (resultat != null)
                            {
                                resultat = maRegleNettoyage.Replace(resultat, "");
                                String hostname = maRegleHostname.Match(resultat).ToString();
                                hostname = maRegleSuppHost.Replace(hostname, "$1");
                                Console.Write(hostname);
                                StreamWriter sw = new StreamWriter(chemin_sauvegarde+"\\"+hostname+"_"+DateMaintenant+".txt");
                                sw.WriteLine(resultat);
                                sw.Close();
                                toolTip2.Show("Sauvegarde effectuée", this, 22, Height - 78, 8000);
                            }
                        }
                        else if (typeCon == "telnet")
                        {
                            //TelnetStream telnet = Connect(add);
                            //telnet.SetRemoteMode(TelnetOption.Echo, false);

                            resultat = CiscoExpectTelnet(add, login, mdp, mdpEn, "show running-config");

                            if (resultat.Length > 0)
                            {
                                if (resultat == "Echec de la connexion")
                                {
                                    toolTip2.Show("Echec de la connexion", this, 22, Height - 78);
                                }
                                else
                                {
                                    resultat = maRegleNettoyage.Replace(resultat, "");
                                    String hostname = maRegleHostname.Match(resultat).ToString();
                                    hostname = maRegleSuppHost.Replace(hostname, "$1");
                                    StreamWriter sw = new StreamWriter(chemin_sauvegarde + "\\" + hostname + "_" + DateMaintenant + ".txt");
                                    sw.WriteLine(resultat);
                                    sw.Close();
                                    toolTip2.Show("Sauvegarde effectuée", this, 22, Height - 78, 8000);
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Les champs login, mot de passe, mdp enable, type de connection doivent être remplis");
                    }
                    }
                }   
        }

        private void buttonRAZ_Click(object sender, EventArgs e)
        {
            this.inventairePrincipal.getTab_equipements().Clear();
            this.rafraichirAffichage();
        }

        private void supprimerÉquipementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String ip;
            foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
            {
                ip = row.Cells[1].Value.ToString();
                this.inventairePrincipal.suppEquipement(ip);
                dataGridViewInventaire.Rows.Remove(row);
            }
            
        }

        private void buttonSaveConf_Click(object sender, EventArgs e)
        {
            String resultat = "";
            Regex maRegleNettoyage = new Regex(@".*#.*|show running-config|Building configuration...|^\n");
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "Sauvegarde";
            saveFile.DefaultExt = "txt";
            saveFile.Filter = "Fichier TXT | *.txt";
            saveFile.FilterIndex = 1;
            saveFile.RestoreDirectory = true;

            try
            {

                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    String chemin_sauvegarde = saveFile.FileName;
                    String choix = (String)comboBoxTypeConn.SelectedItem;
                    if (choix == null)
                    {
                        MessageBox.Show("Vous n'avez pas choisi le type de connexion !");
                    }
                    else
                    {
                        if (choix.Equals("ssh"))
                        {

                            SshShell ssh = new SshShell(textBoxAdd.Text, textBoxLogin.Text, maskedTextBoxMdp.Text);
                            ssh.Connect();
                            Console.WriteLine("OK\n");
                            resultat = CiscoExpectSauvConf(ssh, maskedTextBoxMdpEnable.Text, "show running-config");
                            if (resultat != null)
                            {
                                resultat = maRegleNettoyage.Replace(resultat, "");
                                StreamWriter sw = new StreamWriter(chemin_sauvegarde);
                                sw.WriteLine(resultat);
                                sw.Close();
                                toolTip2.Show("Sauvegarde effectuée", this, 22, Height - 78, 8000);
                            }
                        }
                        else if (choix.Equals("telnet"))
                        {
                            //TelnetStream telnet = Connect(textBoxAdd.Text);
                            //telnet.SetRemoteMode(TelnetOption.Echo, false);

                            resultat = CiscoExpectTelnet(textBoxAdd.Text, textBoxLogin.Text, maskedTextBoxMdp.Text, maskedTextBoxMdpEnable.Text, "show running-config");

                            if (resultat.Length > 0)
                            {
                                if (resultat == "Echec de la connexion")
                                {
                                    toolTip2.Show("Echec de la connexion", this, 22, Height - 78);
                                }
                                else
                                {
                                    resultat = maRegleNettoyage.Replace(resultat, "");
                                    StreamWriter sw = new StreamWriter(chemin_sauvegarde);
                                    sw.WriteLine(resultat);
                                    sw.Close();
                                    toolTip2.Show("Sauvegarde effectuée", this, 22, Height - 78, 8000);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception excep)
            {
                MessageBox.Show("Une erreur c'est produite lors de la sauvegarde : "+ excep.Message);
            }
            
        }

        private TelnetStream Connect(String ip)
        {
            TcpClient cli = new TcpClient(ip, TelnetStream.DefaultPort);
            Stream peer = cli.GetStream();
            TelnetStream telnet = new TelnetStream(peer);
            return telnet;
        }
        
        private static String CiscoExpectTelnet(String add, String login, String mdp, String mdpEn, String command)
        {
            Regex maReglePrompt = new Regex(@">|#");
            Regex maReglePrompt2 = new Regex(@"#");
            Regex maRegleSplit = new Regex(@"\n");
            Telnet telnet = new Telnet(add,23);
            String s = telnet.Login(login,mdp, 3000);
            String[] result = maRegleSplit.Split(s);

            //On verifie que l'on est bien connecté à l'equipement
            if (maReglePrompt.IsMatch(s))
            {
                //Si mode non enable, on passe en enable
                if (result[result.Length - 1].Contains(">"))
                {
                    telnet.WriteLine("enable");
                    telnet.WriteLine(mdpEn);
                }

                //Sinon on lance la commande
                telnet.WriteLine("terminal length 0");
                telnet.WriteLine(command);
            }
            //Sinon
            else
            {
                return "Echec de la connexion";
            }
            return telnet.Read();


            
           /* String resultatConf = null;
            String prompt = "";
            StreamReader reader = new StreamReader(connection, Encoding.ASCII);
            Expector m_xp;
            Regex maRegleFinRun = new Regex(@"^end");
            Regex maReglePrompt = new Regex(@">|#");
            Regex maReglePromptFinal = new Regex(@"#");
            Regex maRegleUsername = new Regex(@"Username|Password");
            m_xp = new Expector(connection);
            m_xp.ExpectTimeout = new TimeSpan(0, 0, 30);
            
            while (!(maRegleUsername.IsMatch(prompt)))
            {
                prompt = reader.ReadLine(); 
            }

            if(prompt.Contains("Username"))
            {
                m_xp.SendLine("");
                m_xp.Expect("Username");
                m_xp.SendLine(login);
            }
            m_xp.SendLine(mdp);
            // Retour à la ligne pour la récupération du prompt
            m_xp.SendLine("");

            while (!(maReglePrompt.IsMatch(prompt)))
            {
                prompt = reader.ReadLine();
            }

            if (prompt.Contains(">"))
            {
                m_xp.SendLine("enable");
                m_xp.Expect("Password:");
                m_xp.SendLine(mdpEn);
            }
            m_xp.SendLine("terminal length 0");
            m_xp.Expect("#");
            m_xp.SendLine(command);
            m_xp.Expect("#");
            m_xp.SendLine("");

            String line = "";
            while (!(maReglePromptFinal.IsMatch(line)))
            {
                if (line != "")
                {
                    resultatConf = resultatConf + "\n" + line;
                }
                line = reader.ReadLine();
            }

            connection.Close();
          
            return resultatConf;*/
            
        }

        private static String CiscoExpectTelnetConfT(TelnetStream connection, String login, String mdp, String mdpEn, String conf)
        {
            String resultatConf = null;
            String prompt = "";
            StreamReader reader = new StreamReader(connection, Encoding.ASCII);
            Expector m_xp;
            Regex maRegleFinRun = new Regex(@"^end");
            Regex maReglePrompt = new Regex(@">|#");
            Regex maRegleUsername = new Regex(@"Username|Password");
            m_xp = new Expector(connection);
            m_xp.ExpectTimeout = new TimeSpan(0, 0, 30);

            while (!(maRegleUsername.IsMatch(prompt)))
            {
                prompt = reader.ReadLine();
            }

            if (prompt.Contains("Username"))
            {
                m_xp.SendLine("");
                m_xp.Expect("Username");
                m_xp.SendLine(login);
            }
            m_xp.SendLine(mdp);
            // Retour à la ligne pour la récupération du prompt
            m_xp.SendLine("");

            while (!(maReglePrompt.IsMatch(prompt)))
            {
                prompt = reader.ReadLine();
            }

            if (prompt.Contains(">"))
            {
                m_xp.SendLine("enable");
                m_xp.SendLine(mdpEn);
            }
            m_xp.SendLine("terminal length 0");
            m_xp.Expect("#");
            m_xp.SendLine("configure terminal");
            m_xp.Expect("#");
            m_xp.SendLine(conf);
            m_xp.Expect("#");
            m_xp.SendLine("");

            String line = "";
            while (!(maReglePrompt.IsMatch(line)))
            {
                if (line != "")
                {
                    resultatConf = resultatConf + "\n" + line;
                }
                line = reader.ReadLine();
            }

            m_xp.SendLine("end");
            m_xp.Expect("#");
            m_xp.SendLine("write memomry");
            m_xp.Expect("#");

            connection.Close();

            return resultatConf;
        }

        private static String CiscoExpectSauvConf(SshShell connection, String mdpEn, String command)
        {
            String resultatConf = null;

            // Début de la connection
            Regex maReglePrompt = new Regex(@">|#");
            Regex maRegleMDP = new Regex(@"Password|#");
            Regex maRegleShRun = new Regex(@".*|More|end");
            // Attente du prompt
            String promptConn = connection.Expect(maReglePrompt);
            if (promptConn.Contains(">"))
            {
                //il faut rentrer en mode privilégié
                connection.WriteLine("enable");
                // Attente du mot de passe
                connection.Expect("Password");
                connection.WriteLine(mdpEn);
                promptConn = connection.Expect(maReglePrompt);
            }
            // Si il y a eu erreur sur le mot de passe ennable
            //if (connection.Expect(maRegleMDP).Contains("#"))
            if(promptConn.Contains("#"))
            {
                // Mot de passe accepté
                // Donc récupération de la configuration
                connection.WriteLine("terminal length 0");
                connection.Expect("#");
                connection.WriteLine(command);
                resultatConf = connection.Expect("#");
            }
            else
            {
                // Demande a nouveau du mot de passe ==> Errreur ==> Déconnexion
                connection.Close();
                MessageBox.Show("Mauvais mot de passe enable");
            }
            
            // Sinon nous sommmes déjà en mode privilégié

            connection.Close();
            return resultatConf;
            
        }

        private void dataGridViewInventaire_MouseClick(object sender, MouseEventArgs e)
        {
            toolTip1.Hide(this);
        }

        private void buttonPoussConf_Click(object sender, EventArgs e)
        {
            
            String resultat = "";
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.DefaultExt = "txt";
            openFile.Filter = "Fichier TXT | *.txt";
            openFile.ShowDialog();
            if (openFile.FileNames.Length > 0)
            {
                String chemin_fichier = openFile.FileNames[0];
                StreamReader readerFichier = new StreamReader(chemin_fichier);
                String conf = readerFichier.ReadToEnd();
                String choix = (String)comboBoxTypeConn.SelectedItem;

                if (choix.Equals("ssh"))
                {
                    SshShell ssh = new SshShell(textBoxAdd.Text, textBoxLogin.Text, maskedTextBoxMdp.Text);
                    ssh.Connect();
                    resultat = CiscoExpectConfT(ssh, maskedTextBoxMdpEnable.Text, conf);
                    toolTip2.Show("Configuration implémentée", this, 22, Height - 78, 8000);
                }
                else if (choix.Equals("telnet"))
                {
                    TelnetStream telnet = Connect(textBoxAdd.Text);
                    telnet.SetRemoteMode(TelnetOption.Echo, false);

                    resultat = CiscoExpectTelnetConfT(telnet, textBoxLogin.Text, maskedTextBoxMdp.Text, maskedTextBoxMdpEnable.Text,conf);
                    toolTip2.Show("Configuration implémentée", this, 22, Height - 78, 8000);
                }
            }
        }

        private static String CiscoExpectConfT(SshShell connection, String mdpEn, String command)
        {
            String resultatConf = null;

            // Début de la connection
            Regex maReglePrompt = new Regex(@">|#");
            Regex maRegleMDP = new Regex(@"Password|#");
            Regex maRegleShRun = new Regex(@".*|More|end");
            // Attente du prompt
            String promptConn = connection.Expect(maReglePrompt);
            if (promptConn.Contains(">"))
            {
                //il faut rentrer en mode privilégié
                connection.WriteLine("enable");
                // Attente du mot de passe
                connection.Expect("Password");
                connection.WriteLine(mdpEn);
                promptConn = connection.Expect(maReglePrompt);
            }
            // Si il y a eu erreur sur le mot de passe ennable
            if (promptConn.Contains("#"))
            {
                // Mot de passe accepté
                // Donc récupération de la configuration
                connection.WriteLine("terminal length 0");
                connection.Expect("#");
                connection.WriteLine("configure terminal");
                connection.Expect("#");
                connection.WriteLine(command);
                resultatConf = connection.Expect("#");
            }
            else
            {
                // Demande a nouveau du mot de passe ==> Errreur ==> Déconnexion
                connection.Close();
                MessageBox.Show("Mauvais mot de passe enable");
            }
            connection.Close();
            return resultatConf;
        }

        private void checkBoxAffichCaractereMdpEn_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBoxAffichCaractereMdpEn.Checked)
            {
                maskedTextBoxMdpEnable.PasswordChar = (char)0;
            }
            else
            {
                maskedTextBoxMdpEnable.PasswordChar = '*';
            }
           
        }

        private void checkBoxAffichCaractereMdp_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxAffichCaractereMdp.Checked)
            {
                maskedTextBoxMdp.PasswordChar = (char)0;
            }
            else
            {
                maskedTextBoxMdp.PasswordChar = '*';
            }
        }

        private void manuellementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            String add;
            String login;
            String mdp;
            String mdpEn;
            String typeCon;
            String resultat = "";
            MessageBoxSaisieCommand MsgBoxCommand = new MessageBoxSaisieCommand();
            if (MsgBoxCommand.ShowDialog() == DialogResult.OK)
            {
                String conf = MsgBoxCommand.getCommand();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    add = row.Cells[1].Value.ToString();
                    login = row.Cells[2].Value.ToString();
                    mdp = row.Cells[3].Value.ToString();
                    mdpEn = row.Cells[4].Value.ToString();
                    typeCon = row.Cells[6].Value.ToString();

                    if (typeCon == "ssh")
                    {
                        SshShell ssh = new SshShell(add, login, mdp);
                        ssh.Connect();
                        resultat = CiscoExpectConfT(ssh, mdpEn, conf);
                        toolTip2.Show("Configuration implémentée", this, 22, Height - 78, 8000);
                    }
                    else if (typeCon == "telnet")
                    {
                        TelnetStream telnet = Connect(add);
                        telnet.SetRemoteMode(TelnetOption.Echo, false);

                        resultat = CiscoExpectTelnetConfT(telnet, login, mdp, mdpEn, conf);
                        toolTip2.Show("Configuration implémentée", this, 22, Height - 78, 8000);
                    }
                }
            }
        }

        private void aPartirDunFichierToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String add;
            String login;
            String mdp;
            String mdpEn;
            String typeCon;
            String resultat = "";
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.DefaultExt = "txt";
            openFile.Filter = "Fichier TXT | *.txt";
            openFile.ShowDialog();
            if (openFile.FileNames.Length > 0)
            {
                String chemin_fichier = openFile.FileNames[0];
                StreamReader readerFichier = new StreamReader(chemin_fichier);
                String conf = readerFichier.ReadToEnd();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    add = row.Cells[1].Value.ToString();
                    login = row.Cells[2].Value.ToString();
                    mdp = row.Cells[3].Value.ToString();
                    mdpEn = row.Cells[4].Value.ToString();
                    typeCon = row.Cells[6].Value.ToString();

                    if (typeCon == "ssh")
                    {
                        SshShell ssh = new SshShell(add, login, mdp);
                        ssh.Connect();
                        resultat = CiscoExpectConfT(ssh, mdpEn, conf);
                        toolTip2.Show("Configuration implémentée", this, 22, Height - 78, 8000);
                    }
                    else if (typeCon == "telnet")
                    {
                        TelnetStream telnet = Connect(add);
                        telnet.SetRemoteMode(TelnetOption.Echo, false);

                        resultat = CiscoExpectTelnetConfT(telnet, login, mdp, mdpEn, conf);
                        toolTip2.Show("Configuration implémentée", this, 22, Height - 78, 8000);
                    }
                }
            }
        }

        private void ConnectShapes(Microsoft.Office.Interop.Visio.Shape shape1, Microsoft.Office.Interop.Visio.Shape shape2, Microsoft.Office.Interop.Visio.Shape connector)
        {
            IVisio.Cell beginXCell = connector.get_CellsSRC(
             (short)IVisio.VisSectionIndices.visSectionObject, (short)IVisio.VisRowIndices.visRowXForm1D,
              (short)IVisio.VisCellIndices.vis1DBeginX);
            // glue the source side of the connector to the first shape
            beginXCell.GlueTo(shape1.get_CellsSRC(
                  (short)IVisio.VisSectionIndices.visSectionObject,
                  (short)IVisio.VisRowIndices.visRowXFormOut,
                  (short)IVisio.VisCellIndices.visXFormPinX));


            // get the cell from the destination side of the connector
            IVisio.Cell endXCell = connector.get_CellsSRC(
            (short)IVisio.VisSectionIndices.visSectionObject,
            (short)IVisio.VisRowIndices.visRowXForm1D,
            (short)IVisio.VisCellIndices.vis1DEndX);


            // glue the destination side of the connector to the second shape
            endXCell.GlueTo(shape2.get_CellsSRC(
            (short)IVisio.VisSectionIndices.visSectionObject,
            (short)IVisio.VisRowIndices.visRowXFormOut,
            (short)IVisio.VisCellIndices.visXFormPinX));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            // Position des éléments dessinés
            double x = 2.0;
            double y = 0.0;

            // Regle pour spliter les voisins récupérés dans le tableau
            Regex maRegleSplit = new Regex(@"\n");

            // Création d'un VIsio
            IVisio.Application application = new IVisio.Application();
            application.Documents.Add("");
            IVisio.Documents visioDocs = application.Documents;
            IVisio.Document visioStencil = visioDocs.OpenEx("PERIPH_U.VSS", (short)IVisio.VisOpenSaveArgs.visOpenDocked);
            IVisio.Document stencilconnector = visioDocs.OpenEx("Basic_U.vss", (short)IVisio.VisOpenSaveArgs.visOpenDocked);
            IVisio.Page visioPage = application.ActivePage;
            IVisio.Master masterConnector = stencilconnector.Masters.get_ItemU("Dynamic connector");
            

            bool equipement_present = false;
            bool voisin_present = false;

            // Dictionnaire des éléments déssinés (equipement + leurs voisins associés)
            Dictionary<IVisio.Shape, List<IVisio.Shape>> paire_equip = new Dictionary<IVisio.Shape, List<IVisio.Shape>>();

            IVisio.Shape equip_stock = null;

            // Pour chaque equipement (utilisation de la vue)
            foreach (DataGridViewRow row in dataGridViewInventaire.Rows)
            {
                //Récupération nom et voisins
                String equipement = row.Cells[0].Value.ToString();
                String voisin = row.Cells[9].Value.ToString();
                String ports = row.Cells[10].Value.ToString();
                String[] tab_temp1 = maRegleSplit.Split(voisin);
                String[] tab_ports = maRegleSplit.Split(ports);
                voisin_present = false;
                equipement_present = false;

                //Parcours la liste des équipements dessinés
                foreach (IVisio.Shape equip_dessine in paire_equip.Keys)
                {
                    //test si l'équipement en cours est déjà dessiné
                    if (equip_dessine.Text.Equals(equipement))
                    {
                        equipement_present = true;
                        // On stock l'objet "Dessin de l'équipement"
                        equip_stock = equip_dessine;
                        break;
                    }
                }
                
                //Si l'equipement n'est pas déjà dessiné
                if (!equipement_present)
                {
                    // On dessine l'équipement
                    IVisio.Master visioEquipMaster = visioStencil.Masters.get_ItemU(@"Hub");
                    IVisio.Shape visioEquipShape = visioPage.Drop(visioEquipMaster, x, y);
                    
                    visioEquipShape.Text = equipement;
                    //Ajout dans la liste des dessinés
                    paire_equip.Add(visioEquipShape,new List<IVisio.Shape>());

                    // Parcours des voisins de cet équipement
                    for (int i = 0; i < tab_temp1.Length - 1; i++)
                    {
                        
                        //Parcours la liste des équipements dessinés
                        foreach (IVisio.Shape voisin_dessine in paire_equip.Keys)
                        {
                            //test si le voisin en cours est déjà dessiné
                            if (voisin_dessine.Text.Equals(tab_temp1[i]))
                            {
                                voisin_present = true;
                                // On fait le lien entre l'équipement et son voisin
                                //IVisio.Shape connector = visioPage.Shapes.get_ItemU("Dynamic connector");
                                //IVisio.Shape connector = visioPage.Drop(masterConnector, x, y);
                                //connector.Text = tab_temp1[i] + " : " + tab_ports[i];
                                //ConnectShapes(voisin_dessine, visioEquipShape, connector);
                                visioEquipShape.AutoConnect(voisin_dessine, IVisio.VisAutoConnectDir.visAutoConnectDirLeft, voisin_dessine);
                                // On ajoute la paire équipement/voisin déssinée et reliée dans le dictionnaire
                                paire_equip[visioEquipShape].Add(voisin_dessine);
                                paire_equip[voisin_dessine].Add(visioEquipShape);
                                break;
                            }
                        }
                        // Si le voisin n'est pas déjà dessiné
                        if (!voisin_present)
                        {
                            // On dessine le voisin
                            IVisio.Master visioVoisinMaster = visioStencil.Masters.get_ItemU(@"Hub");
                            IVisio.Shape visioVoisinShape = visioPage.Drop(visioVoisinMaster, x, y);
                            
                            visioVoisinShape.Text = tab_temp1[i];
                            // On ajoute le voisin dans la liste des éléments dessinés
                            paire_equip.Add(visioVoisinShape, new List<IVisio.Shape>());
                            // On fait le lien entre l'équipement et son voisin
                            //IVisio.Shape connector = visioPage.Drop(masterConnector, x, y);
                            //connector.Text = tab_temp1[i] + " : " + tab_ports[i];
                            //ConnectShapes(visioEquipShape, visioVoisinShape, connector);
                            visioEquipShape.AutoConnect(visioVoisinShape, IVisio.VisAutoConnectDir.visAutoConnectDirLeft, visioVoisinShape);
                            // On ajoute la paire équipement/voisin déssinée et reliée dans le dictionnaire
                            paire_equip[visioEquipShape].Add(visioVoisinShape);
                            paire_equip[visioVoisinShape].Add(visioEquipShape);
                        }
                        voisin_present = false;
                    }
                }
                // Si l'équipement est déjà dessiné
                else
                {
                    // Parcours des voisins de cet équipement
                    for (int i = 0; i < tab_temp1.Length - 1; i++)
                    {
                        //Parcours la liste des équipements dessinés
                        foreach (IVisio.Shape voisin_dessine in paire_equip.Keys)
                        {
                            //test si le voisin en cours est déjà dessiné
                            if (voisin_dessine.Text.Equals(tab_temp1[i]))
                            {
                                voisin_present = true;
                                // On test si le lien entre l'équipement et le voisin est déjà déssiné
                                if (paire_equip[voisin_dessine].Contains(equip_stock))
                                {

                                }
                                else
                                {
                                    // On fait le lien entre l'équipement et son voisin
                                    //IVisio.Shape connector = visioPage.Shapes.get_ItemU("Dynamic connector");
                                    //IVisio.Shape connector = visioPage.Drop(masterConnector, x, y);
                                    //connector.Text = tab_temp1[i]+" : "+tab_ports[i];
                                    //ConnectShapes(equip_stock, voisin_dessine, connector);
                                    equip_stock.AutoConnect(voisin_dessine, IVisio.VisAutoConnectDir.visAutoConnectDirLeft, voisin_dessine);
                                    // On ajoute la paire équipement/voisin déssinée et reliée dans le dictionnaire
                                    paire_equip[voisin_dessine].Add(equip_stock);
                                    paire_equip[equip_stock].Add(voisin_dessine);
                                }
                            }
                        }
                        // Si le voisin n'est pas déjà dessiné
                        if (!voisin_present)
                        {
                            // On dessine le voisin
                            IVisio.Master visioVoisinMaster = visioStencil.Masters.get_ItemU(@"Hub");
                            IVisio.Shape visioVoisinShape = visioPage.Drop(visioVoisinMaster, x, y);
                            visioVoisinShape.Text = tab_temp1[i];
                            //IVisio.Shape connector = visioPage.Shapes.get_ItemU("Dynamic connector");
                            //IVisio.Shape connector = visioPage.Drop(masterConnector, x, y);
                            //connector.Text = tab_temp1[i] + " : " + tab_ports[i];
                            //connector.get_CellsU("TxtAngle").set_Result(IVisio.VisUnitCodes.visAngleUnits,180);
                            // On ajoute le voisin dans la liste des éléments dessinés
                            paire_equip.Add(visioVoisinShape, new List<IVisio.Shape>());
                            // On fait le lien entre l'équipement et son voisin
                            //ConnectShapes(equip_stock, visioVoisinShape, connector);
                            equip_stock.AutoConnect(visioVoisinShape, IVisio.VisAutoConnectDir.visAutoConnectDirLeft, visioVoisinShape);
                            // On ajoute la paire équipement/voisin déssinée et reliée dans le dictionnaire
                            paire_equip[equip_stock].Add(visioVoisinShape);
                            paire_equip[visioVoisinShape].Add(equip_stock);
                        }
                        voisin_present = false;
                    }
                    
                }
                //On décale la position du prochain équipement
                y = y + 0.7;
               
            }
            // On choisit une disposition "Circulaire"
            application.ActivePage.PageSheet.get_CellsU("PlaceStyle").FormulaU = "6";
            // On choisit des liens "Centre vers Centre"
            application.ActivePage.PageSheet.get_CellsU("RouteStyle").FormulaU = "16";
            // On recharge la page Visio
            application.ActivePage.Layout();
            // On ajuste la page à la taille du dessin
            application.ActivePage.ResizeToFitContents();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            SimpleSnmp snmp = new SimpleSnmp(textBox1.Text, 161, textBox2.Text, 1000, 0);
            Dictionary<Oid, AsnType> ifname;
            Dictionary<Oid, AsnType> ifoperstatus;
            Dictionary<Oid, AsnType> sysUpTime;
            Dictionary<Oid, AsnType> iflastchange;
            String ifName="";
            String ifOperStatus="";
            String SysUpTime="";
            int sysDay = 0;
            String sysHour = "";
            String sysMin = "";
            int sysH = 0;
            int sysM = 0;
            int lastDay = 0;
            String lastHour = "";
            String lastMin = "";
            int lastH = 0;
            int lastM = 0;
            String ifLastChange="";
            String[] tab_temp;
            ArrayList tab_ifname = new ArrayList(); ;
            ArrayList tab_ifoperstatus = new ArrayList(); ;
            ArrayList tab_iflastchange = new ArrayList();
            Regex maRegleifoperstatusUP = new Regex(@"1");
            Regex maRegleifoperstatusDOWN = new Regex(@"2");
            Regex maReglesysDay = new Regex(@"(\n)*d.*(\n)*");
            Regex maReglesysHour = new Regex(@"(\n)*.*d ");
            Regex maReglesysHour2 = new Regex(@"h.*(\n)*");
            Regex maReglesysMin = new Regex(@"(\n)*.*h ");
            Regex maReglesysMin2 = new Regex(@"m.*(\n)*");
            Regex maRegleSplit = new Regex(@"\n");

            //Récupération SNMP des informations
            ifname = snmp.Walk(SnmpVersion.Ver2, "1.3.6.1.2.1.31.1.1.1.1");
            ifoperstatus = snmp.Walk(SnmpVersion.Ver2, "1.3.6.1.2.1.2.2.1.8");
            sysUpTime = snmp.Walk(SnmpVersion.Ver2, "1.3.6.1.2.1.1.3");
            iflastchange = snmp.Walk(SnmpVersion.Ver2, "1.3.6.1.2.1.2.2.1.9");

            if (ifname == null | ifoperstatus == null | sysUpTime == null | iflastchange == null)
            {
                MessageBox.Show("Le check des ports à echoué");
            }
            else
            {
                //On recupère le nom des inerfaces
                foreach (KeyValuePair<Oid, AsnType> kvp in ifname)
                {
                    ifName = ifName + kvp.Value.ToString() + "\n";

                }
                //On stock chaque nom d'interface dans un tableau
                tab_temp = maRegleSplit.Split(ifName);
                //On stock chaque nom d'interface dans une liste
                for (int i = 0; i < tab_temp.Length; i++)
                {
                    tab_ifname.Add(tab_temp[i]);
                }

                //On recupere le status des interfaces
                foreach (KeyValuePair<Oid, AsnType> kvp in ifoperstatus)
                {
                    ifOperStatus = ifOperStatus + kvp.Value.ToString() + "\n";
                    ifOperStatus = maRegleifoperstatusUP.Replace(ifOperStatus, "UP");
                    ifOperStatus = maRegleifoperstatusDOWN.Replace(ifOperStatus, "DOWN");
                }
                //On stock le status de chaque interface dans un tableau
                tab_temp = maRegleSplit.Split(ifOperStatus);
                //On stock le status de chaque interface dans une liste
                for (int i = 0; i < tab_temp.Length; i++)
                {
                    tab_ifoperstatus.Add(tab_temp[i]);
                }

                //On récupère le sysUpTime
                foreach (KeyValuePair<Oid, AsnType> kvp in sysUpTime)
                {
                    SysUpTime = kvp.Value.ToString();

                    sysDay = int.Parse(maReglesysDay.Replace(SysUpTime, ""));
                    sysHour = maReglesysHour.Replace(SysUpTime, "");
                    sysHour = maReglesysHour2.Replace(sysHour, "");
                    sysH = int.Parse(sysHour);
                    sysMin = maReglesysMin.Replace(SysUpTime, "");
                    sysMin = maReglesysMin2.Replace(sysMin, "");
                    sysM = int.Parse(sysMin);
                }

                //On récupère le dernier changement de chaque interface
                foreach (KeyValuePair<Oid, AsnType> kvp in iflastchange)
                {
                    ifLastChange = kvp.Value.ToString() + "\n";
                    lastDay = int.Parse(maReglesysDay.Replace(ifLastChange, ""));
                    //Depuis combien de jours il est dans cet état
                    lastDay = sysDay - lastDay;

                    lastHour = maReglesysHour.Replace(ifLastChange, "");
                    lastH = int.Parse(maReglesysHour2.Replace(lastHour, ""));
                    //Depuis combien d'heures il est dans cet état
                    lastH = sysH - lastH;
                    if (lastH < 0)
                    {
                        lastH = 24 + lastH;
                    }

                    lastMin = maReglesysMin.Replace(ifLastChange, "");
                    lastM = int.Parse(maReglesysMin2.Replace(lastMin, ""));

                    //Depuis combien de minutes il est dans cet état
                    lastM = sysM - lastM;
                    if (lastM < 0)
                    {
                        lastM = 60 + lastM;
                        lastH = lastH - 1;
                    }

                    //On rassemble jour, heure et minute pour obtenir une date
                    String lastChange = lastDay + "d " + lastH + "h " + lastM + "m";
                    //On stock la date dans une liste
                    tab_iflastchange.Add(lastChange);
                }

                for (int i = 0; i < tab_ifname.Count - 1; i++)
                {
                    //Si le user veut l'affichage des ports DOWN
                    if (radioButtonDOWN.Checked == true)
                    {
                        //On récupère dans la liste des status toutes les interfaces DOWN
                        if (tab_ifoperstatus[i].ToString().Contains("DOWN"))
                        {
                            richTextBox1.Text = richTextBox1.Text + (tab_ifname[i] + " est " + tab_ifoperstatus[i] + " depuis " + tab_iflastchange[i]) + "\n";
                        }
                    }
                    //Si le user veut l'affichage des ports UP
                    else if (radioButtonUP.Checked == true)
                    {
                        //On récupère dans la liste des status toutes les interfaces UP
                        if (tab_ifoperstatus[i].ToString().Contains("UP"))
                        {
                            richTextBox1.Text = richTextBox1.Text + (tab_ifname[i] + " est " + tab_ifoperstatus[i] + " depuis " + tab_iflastchange[i]) + "\n";
                        }
                    }
                    //Si le user veut l'affichage de tous les états
                    else
                    {
                        richTextBox1.Text = richTextBox1.Text + (tab_ifname[i] + " est " + tab_ifoperstatus[i] + " depuis " + tab_iflastchange[i]) + "\n";
                    }
                }
            }
        }

        private void Ping(String ip, int nb_repetition)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();

            String data = new String('a', 32);
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 1000;
            DateTime Maintenant = DateTime.Now;
            String DateMaintenant = Maintenant.ToString("HH'h'mm'm'ss");
            PingReply reply = pingSender.Send(ip, timeout, buffer, options);

            _pool.WaitOne();
            if (reply.Status == IPStatus.Success)
            {
                if (reply.RoundtripTime > int.Parse(textBoxTimePing.Text))
                {
                    resultats[nb_repetition] = resultats[nb_repetition] + ip + " : Ping NOK : " + reply.RoundtripTime + " ms\n";
                    logs[0].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + ip + " : Ping NOK : " + reply.RoundtripTime + " ms\n");
                }
                else
                {
                    logs[0].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + ip + " : Ping OK : " + reply.RoundtripTime + " ms\n");
                }
            }
            else
            {
                resultats[nb_repetition] = resultats[nb_repetition] +ip + " : Ping NOK \n";
                logs[0].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + ip + " : Ping NOK \n");
            }
            _pool.Release();
        }

        private void Tcping(String ip, int port,int nb_repetition)
        {
            DateTime Maintenant = DateTime.Now;
            String DateMaintenant = Maintenant.ToString("HH'h'mm'm'ss");
            try
            {
                TcpClient tcpping = new TcpClient();
                tcpping.ReceiveTimeout = 2000;
                tcpping.Connect(ip, port);
                _pool.WaitOne();
                logs[1].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + ip + ":" + port + " : TCPPing OK\n");
                tcpping.Close();
                _pool.Release();
            }
            catch (Exception exp)
            {
                _pool.WaitOne();
                Console.WriteLine(exp.Message);
                resultats[nb_repetition] = resultats[nb_repetition] + ip + ":" + port + " : TCPPing NOK\n";
                logs[1].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + ip + ":" + port + " : TCPPing NOK : " + exp.Message + "\n");
                _pool.Release();
            }
        }

        private void Nslookup(String nom, int nb_repetition)
        {
            DateTime Maintenant = DateTime.Now;
            String DateMaintenant = Maintenant.ToString("HH'h'mm'm'ss");
            try
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(nom);
                IPAddress[] ips = hostEntry.AddressList;
                _pool.WaitOne();
                logs[2].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + nom + " :\n");
                foreach (IPAddress ip in ips)
                {
                    logs[2][logs[2].Count-1]= logs[2][logs[2].Count-1]+ip + "\n";
                }
                _pool.Release();
            }
            catch (Exception ex)
            {
                _pool.WaitOne();
                resultats[nb_repetition] = resultats[nb_repetition] + nom + " : Hôte introuvable\n\n";
                logs[2].Add("vague " + (nb_repetition + 1).ToString("D4") + " -> " + DateMaintenant + " -> " + nom + " : Hôte introuvable\n\n");
                _pool.Release();
            }
            
        }

        private void buttonTests_Click(object sender, EventArgs e)
        {
            if (textBoxNb_repetition.Text.Equals("") || textBoxTime.Text.Equals("") || textBoxTime.Text.Equals("0"))
            {
                MessageBox.Show("Veuillez remplir correctement tous les champs");
            }
            else
            {
                if (richTextBoxPing.Lines.Length > 0 && textBoxTimePing.Text.Equals(""))
                {
                    MessageBox.Show("Veuillez remplir le temps pour le Ping");
                }
                else
                {
                    _pool = new Semaphore(0, 1);
                    List<Thread> listThread = new List<Thread>();
                    richTextBoxResultat.Text = "";
                    logs.Clear();
                    listBoxRes.Items.Clear();
                    resultats.Clear();

                    logs.Add(new List<String>());
                    logs.Add(new List<String>());
                    logs.Add(new List<String>());

                    for (int j = 0; j < int.Parse(textBoxNb_repetition.Text); j++)
                    {
                        resultats.Add("");
                        // PING
                        for (int i = 0; i < richTextBoxPing.Lines.Length; i++)
                        {
                            String ip = new String(richTextBoxPing.Lines[i].ToCharArray());
                            listThread.Add(new Thread(() => Ping(ip, j)));
                            listThread[listThread.Count - 1].Start();
                        }

                        // TCP PING
                        for (int i = 0; i < richTextBoxTcping.Lines.Length; i++)
                        {
                            String ip = new String(richTextBoxTcping.Lines[i].ToCharArray());
                            int port = int.Parse(richTextBoxPort.Lines[i]);
                            listThread.Add(new Thread(() => Tcping(ip, port, j)));
                            listThread[listThread.Count - 1].Start();
                        }

                        //NSLOOKUP
                        for (int i = 0; i < richTextBoxNslookup.Lines.Length; i++)
                        {
                            String nom = new String(richTextBoxNslookup.Lines[i].ToCharArray());
                            listThread.Add(new Thread(() => Nslookup(nom, j)));
                            listThread[listThread.Count - 1].Start();
                        }

                        Thread.Sleep(int.Parse(textBoxTime.Text) * 1000);
                    }
                    _pool.Release(1);
                    for (int i = 0; i < listThread.Count; i++)
                    {
                        listThread[i].Join();
                    }
                    for (int i = 1; i <= resultats.Count; i++)
                    {
                        listBoxRes.Items.Add("resultat " + i);
                    }
                    listBoxLogs.Enabled = true;

                }
            }
        }

        private void listBoxLogs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBoxLogs.SelectedIndex.Equals(0))
            {
                richTextBoxResultat.Clear();
                logs[0].Sort();
                for (int i = 0; i < logs[0].Count; i++)
                {
                    richTextBoxResultat.Text += logs[0][i];
                }
            }
            else if (listBoxLogs.SelectedIndex.Equals(1))
            {
                richTextBoxResultat.Clear();
                logs[1].Sort();
                for (int i = 0; i < logs[1].Count; i++)
                {
                    richTextBoxResultat.Text += logs[1][i];
                }
            }
            else if (listBoxLogs.SelectedIndex.Equals(2))
            {
                richTextBoxResultat.Clear();
                logs[2].Sort();
                for (int i = 0; i < logs[2].Count; i++)
                {
                    richTextBoxResultat.Text += logs[2][i];
                }
            }
        }

        private void listBoxRes_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < resultats.Count; i++)
            {
                if (listBoxRes.SelectedIndex.Equals(i))
                {
                    richTextBoxResultat.Text = resultats[i];
                }
            }
        }

        // Est lancé lors de la fin de l'édition d'une case
        private void dataGridViewInventaire_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            String champ_modifie = ((DataGridView)sender).Columns[e.ColumnIndex].Name;
            String valeur_modifie = ((DataGridView)sender).CurrentCell.Value.ToString();
            String ip = ((DataGridView)sender).Rows[e.RowIndex].Cells[1].Value.ToString();

            //On parcourt les equipements de l'inventaire
            foreach (Equipement equip in this.inventairePrincipal.getTab_equipements())
            {
                //On récupère l'équipement correspondant à celui modifié
                if (ip.Equals(equip.getIp()))
                {
                    //On remplace la valeur correspondante de l'équipement par celle éditée dans le tableau 
                    switch (champ_modifie)
                    {
                        case "Nom" :
                            equip.setNom(valeur_modifie);
                            break;
                        case "User":
                            equip.setUser(valeur_modifie);
                            break;
                        case "Mdp":
                            equip.setMdp(valeur_modifie);
                            break;
                        case "Mdp_enable":
                            equip.setMdp_enable(valeur_modifie);
                            break;
                        case "Communaute":
                            equip.setCommunaute(valeur_modifie);
                            break;
                        case "Type_connexion":
                            try
                            {
                                equip.setType_connexion(valeur_modifie);
                            }
                            catch (Exception)
                            {
                                MessageBox.Show("Erreur : Ce champs n'accepte que ssh ou telnet");
                                this.rafraichirAffichage();
                            }
                            break;
                        case "Serial_number":
                            equip.setSerial_number(valeur_modifie);
                            break;
                        case "Description":
                            equip.setDescription(valeur_modifie);
                            break;
                        case "Voisins":
                            // Non editables
                            break;
                        case "Port_voisin":
                            // Non editable
                            break;
                    }
                    //Pour sortir du foreach
                    break; 
                }  
            }
        }

        private void buttonMobaXterm_Click(object sender, EventArgs e)
        {
            Process.Start("MobaXterm_Personal_4.4.exe");
        }

        private void userToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String ip;
            Modification_equipement MsgBoxCommand = new Modification_equipement();
            if (MsgBoxCommand.ShowDialog() == DialogResult.OK)
            {
                String new_user = MsgBoxCommand.getValeur();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    ip = row.Cells[1].Value.ToString();
                    foreach (Equipement equip in this.inventairePrincipal.getTab_equipements())
                    {
                        if (ip.Equals(equip.getIp()))
                        {
                            equip.setUser(new_user);
                            row.Cells[2].Value = new_user;
                            break;
                        }
                    }

                }
            }
        }

        private void motDePasseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String ip;
            Modification_equipement MsgBoxCommand = new Modification_equipement();
            if (MsgBoxCommand.ShowDialog() == DialogResult.OK)
            {
                String new_mdp = MsgBoxCommand.getValeur();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    ip = row.Cells[1].Value.ToString();
                    foreach (Equipement equip in this.inventairePrincipal.getTab_equipements())
                    {
                        if (ip.Equals(equip.getIp()))
                        {
                            equip.setMdp(new_mdp);
                            row.Cells[3].Value = new_mdp;
                            break;
                        }
                    }

                }
            }
        }

        private void motDePasseEnableToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String ip;
            Modification_equipement MsgBoxCommand = new Modification_equipement();
            if (MsgBoxCommand.ShowDialog() == DialogResult.OK)
            {
                String new_mdpEn = MsgBoxCommand.getValeur();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    ip = row.Cells[1].Value.ToString();
                    foreach (Equipement equip in this.inventairePrincipal.getTab_equipements())
                    {
                        if (ip.Equals(equip.getIp()))
                        {
                            equip.setMdp_enable(new_mdpEn);
                            row.Cells[4].Value = new_mdpEn;
                            break;
                        }
                    }

                }
            }
        }

        private void communautéToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String ip;
            Modification_equipement MsgBoxCommand = new Modification_equipement();
            if (MsgBoxCommand.ShowDialog() == DialogResult.OK)
            {
                String new_community = MsgBoxCommand.getValeur();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    ip = row.Cells[1].Value.ToString();
                    foreach (Equipement equip in this.inventairePrincipal.getTab_equipements())
                    {
                        if (ip.Equals(equip.getIp()))
                        {
                            equip.setCommunaute(new_community);
                            row.Cells[5].Value = new_community;
                            break;
                        }
                    }

                }
            }
        }

        private void typeDeConnexionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String ip;
            Modification_equipement MsgBoxCommand = new Modification_equipement();
            if (MsgBoxCommand.ShowDialog() == DialogResult.OK)
            {
                String new_typeCon = MsgBoxCommand.getValeur();
                foreach (DataGridViewRow row in dataGridViewInventaire.SelectedRows)
                {
                    ip = row.Cells[1].Value.ToString();
                    foreach (Equipement equip in this.inventairePrincipal.getTab_equipements())
                    {
                        if (ip.Equals(equip.getIp()))
                        {
                            equip.setType_connexion(new_typeCon);
                            row.Cells[6].Value = new_typeCon;
                            break;
                        }
                    }

                }
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            Help.ShowPopup(this, "Cet onglet permet d'effectuer des tests.\nL'objectif est de lancer X série(s) de tests toutes les X seconde(s).", Cursor.Position);
        }

        private void textBoxAdresse_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.')
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
        }

        private void textBoxAdresse_Leave(object sender, EventArgs e)
        {
            if (((TextBox)sender).Text != "")
            {
                int octet = int.Parse(((TextBox)sender).Text);
                if (octet >= 255 || octet <= 0)
                {
                    ((TextBox)sender).Text = "1";
                }
            }
        }




    }
}
